<template>
	<div>
		<!-- <div>
			<button @click="printEditorHtml">print html</button>
			&nbsp;| &nbsp;
			<button @click="insertTextHandler">insert text</button>
			&nbsp;| &nbsp;
			<button @click="disableHandler">disable</button>
		</div> -->
		<div style="border: 1px solid #ccc; margin-top: 10px; z-index:10000" v-loading="errorLoading">
			<!-- 工具栏 -->
			<Toolbar style="border-bottom: 1px solid #ccc" :editor="editor" :defaultConfig="toolbarConfig" />
			<!-- 编辑器 -->
			<Editor
				style="height: 400px; overflow-y: hidden;"
				:defaultConfig="editorConfig"
				v-model="html"
				@onChange="onChange"
				@onCreated="onCreated"
			/>
		</div>

		<br />
		<el-form>
			<el-form-item label="纠错" v-if="errorslist.length">
				<div style="overflow: auto; max-height: 135px">
					<el-tag
						style="margin-bottom: 10px; display: flex; justify-content: space-between; align-items: center"
						type="primary"
						class="corr-item"
						v-for="(item, index) in errorslist"
						:key="index"
						closable
						@close="onCorrErrorList(index)"
					>
						文字位置: {{ item[2] + 1 }} 原文: {{ item[1] }} : 建议变更: &lt;{{ item[0] }}&gt;

						<el-button style="margin-left: auto;" type="primary" size="mini" @click="onScrollSelectError(item)">
							定位
						</el-button>
					</el-tag>
				</div>
			</el-form-item>
			<el-form-item v-if="errorMessage">
				<el-tag type="danger">{{ errorMessage }}</el-tag>
			</el-form-item>
		</el-form>
		<!-- 跟new Vue的id一致 -->
		<div id="fortressRSPModal"></div>
	</div>
</template>

<script>
import { Boot, DomEditor } from "@wangeditor/editor"
import ModelMenu from "./modelMenu"
import { Editor, Toolbar } from "@wangeditor/editor-for-vue"
import TextCorrectionButton from "./correction"

//注册新的按钮菜单
const menu1Conf = {
	key: "fortressResSel", // 定义 menu key ：要保证唯一、不重复（重要）
	factory() {
		return new ModelMenu() // 把 `YourMenuClass` 替换为你菜单的 class
	},
}
Boot.registerMenu(menu1Conf)
Boot.registerMenu({
	key: "textCorrection",
	factory() {
		return new TextCorrectionButton()
	},
})

export default {
	name: "FortressWangEditor",
	props: ["value"],
	components: { Editor, Toolbar },
	data() {
		return {
			editor: null,
			html: this.value ? this.value : "",
			toolbarConfig: {
				insertKeys: {
					index: 23,
					keys: ["fortressResSel", "textCorrection"], // show menu in toolbar
				},
				excludeKeys: ["group-image"],
				// toolbarKeys: [ /* 显示哪些菜单，如何排序、分组 */ ],
				// excludeKeys: [ /* 隐藏哪些菜单 */ ],
			},
			editorConfig: {
				placeholder: "请输入内容...",
				// autoFocus: false,
				// 所有的菜单配置，都要在 MENU_CONF 属性下
				MENU_CONF: {
					uploadImage: {
						server: window.$conf.commonConf.baseUrl + "/system/oss/upload",
						fieldName: "upfile",
						// 上传进度的回调函数
						onProgress(progress) {
							// progress 是 0-100 的数字
							// console.log("progress", progress)
						},
						customInsert(res, insertFn) {
							// JS 语法
							// res 即服务端的返回结果
							if (res.code == 0) {
								// 从 res 中找到 url alt href ，然后插入图片
								insertFn(res.data.url, res.data.name, res.data.url)
							}
						},
					},
					uploadVideo: {
						server: window.$conf.commonConf.baseUrl + "/system/oss/upload",
						fieldName: "upfile",
						// 上传进度的回调函数
						onProgress(progress) {
							// progress 是 0-100 的数字
							// console.log("progress", progress)
						},
						customInsert(res, insertFn) {
							// JS 语法
							// res 即服务端的返回结果
							if (res.code == 0) {
								// 从 res 中找到 url alt href ，然后插入图片
								insertFn(res.data.url, res.data.name, res.data.url)
							}
						},
					},
				},
			},

			errorslist: [],
			errorLoading: false,
			errorMessage: "",
		}
	},
	methods: {
		onCreated(editor) {
			this.editor = Object.seal(editor) // 【注意】一定要用 Object.seal() 否则会报错
			// console.log(this.editor.getAllMenuKeys()) 获取所有的menuKeys
			// console.log(this.editor.getMenuConfig("uploadVideo")) // 获取 uploadImage 的当前配置

			editor.on("errorslist", errorslist => {
				this.errorslist = errorslist
			})
			editor.on("startLoading", () => {
				this.errorLoading = true
			})
			editor.on("endLoading", errorMessage => {
				this.errorLoading = false
				this.errorMessage = errorMessage
			})
		},
		onChange(editor) {
			// console.log("onChange", editor.getHtml()) // onChange 时获取编辑器最新内容
			this.$emit("input", editor.getHtml())
		},
		insertTextHandler() {
			const editor = this.editor
			if (editor == null) return
			editor.insertText(" hello ")
		},
		printEditorHtml() {
			const editor = this.editor
			if (editor == null) return
			// console.log(editor.getHtml())
		},
		disableHandler() {
			const editor = this.editor
			if (editor == null) return
			editor.disable()
		},
		getText() {
			return this.editor.getText()
		},

		onScrollSelectError(item) {
			const id = item.element.id

			if (!this.editor) {
				return
			}
			this.editor.scrollToElem(id)

			this.editor.focus()
			const newSelection = {
				anchor: { path: [item.line, 0], offset: item.position },
				focus: { path: [item.line, 0], offset: +item.position + 1 },
			}
			this.editor.select(newSelection)
		},
		onCorrErrorList(index) {
			this.errorslist.splice(index, 1)
		},
	},
	mounted() {
		// this.editor.setHtml(this.value)
		// 模拟 ajax 请求，异步渲染编辑器
		// setTimeout(() => {
		// 	this.html = "<p>Ajax 异步设置内容 HTML</p>"
		// }, 1500)
	},
	watch: {
		value: {
			handler(val) {
				this.editor.setHtml(val)
			},
			immediate: false,
		},
	},
	beforeDestroy() {
		const editor = this.editor
		if (editor == null) return
		editor.destroy() // 组件销毁时，及时销毁 editor ，重要！！！
	},
}
</script>

<style src="@wangeditor/editor/dist/css/style.css"></style>
